package iss.java;

import com.sun.xml.internal.ws.api.pipe.ThrowableContainerPropertySet;
import iss.java.list.MyList;
import iss.java.list.Node;

import javax.swing.plaf.synth.SynthRadioButtonMenuItemUI;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by wenke on 2016/9/16.
 */
public class Main_A {
    public static void main(String[] args) throws InterruptedException ,BrokenBarrierException
    {
        MyList list = new MyList();
        list.insert(list.getHead(), 5);
        list.insert(list.getHead(), 4);
        list.insert(list.getHead(), 3);
        list.insert(list.getHead(), 1);
        list.insert(list.getHead(), 0);

        Node node=list.getHead().getNext();

        Thread a=new Thread(new WriteData(node,1));
        Thread b=new Thread(new WriteData(node,2));
        Thread c=new Thread(new WriteData(node,3));
        Thread d=new Thread(new WriteData(node,-1));
        Thread e=new Thread(new WriteData(node,-2));
        Thread f=new Thread(new WriteData(node,-3));

        Thread g=new Thread(new ReadData(node));
        Thread h=new Thread(new ReadData(node));


        g.start();
        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
        f.start();
        h.start();

        Thread.sleep(5000);
        System.out.println();
        System.out.println(node.getData());

        Thread j=new Thread(new ReadData(node));
        j.start();

    }
}

class WriteData implements Runnable{
    private Node node;
    private int number;
    private ReadWriteLock rwlock=new ReentrantReadWriteLock();

    public WriteData(Node node, int number){
        this.node=node;
        this.number=number;
    }

    public void run(){
        rwlock.writeLock().lock();
        try {
            for (int i = 0; i <100 ; i++) {
                node.setData(node.getData()+number);
            }
            System.out.println(number*100+"done. "+"now"+node.getData());

        }
        finally{
            rwlock.writeLock().unlock();
        }

    }
}

class ReadData implements Runnable{
    private Node node;
    private ReadWriteLock rwlock=new ReentrantReadWriteLock();

    public ReadData(Node node){
        this.node=node;
    }

    public void run(){
        rwlock.readLock().lock();
        try {
            System.out.println(node.getData());
        }finally{
            rwlock.readLock().unlock();
        }

    }
}